<?php
namespace Home\Controller;
class PayController extends HomeController {
    protected function _initialize(){
    	parent::_initialize();
    }
	public function surecode(){
        !is_login() && $this->error('请先登录', U('login/index'));
		$user_code_id = intval(I('user_code_id'));
		$user_code_info = M('user_code')->find($user_code_id);
		// 判断活动信息
		$snatch_info = M('snatch')->find($user_code_info['snatch_id']);
		if ($snatch_info['status'] != 1) {
			$this->error("本次活动已结束，请参加下期活动");
		}
		if ($user_code_info['status'] != 0) {
			$this->error("您已支付幸运号，请等待开奖",U('index/index'));
		}	
		$last_time = C("pay_timeout") - (time() - $user_code_info['add_time']);
		if ($last_time <= 0) {
			$last_time = 0;
			M('user_code')->delete($user_code_id);
			$this->error("支付超时，请重新获取幸运码",U('getCode',['id'=>$snatch_id]));
		}
		$user_amount = M('member')->where('uid='.UID)->getField('amount');
		$this->assign('user_amount',$user_amount);
		$this->assign('user_code_id',$user_code_id);
		$this->assign("code",$user_code_info['code']);
		$this->assign('snatch_info',$snatch_info);
		$this->assign('last_time',$last_time);
		// if (is_wechat()) {
		// 	$jsApiParameters = $this->getWxpayinfo($user_code_info['pay_sn'],$snatch_info['money']);
		// 	$this->assign('jsApiParameters',$jsApiParameters);
		// }
		$this->display();
	}
	/**
	 * 支付幸运号添加记录
	 * @return [type] [description]
	 */
	public function pay(){
        !is_login() && $this->error('请先登录', U('login/index'));
		$pay_type = I('pay_type');
		$id = I('id');
		$info = M('user_code')->where(array('id'=>$id,'uid'=>UID))->find();
		if (empty($info)) {
			$this->error("支付信息错误");
		}
		if ($pay_type == 'money') {
			$user_amount = M('member')->where('uid='.UID)->getField('amount');
			if ($user_amount < $info['money']) {
				$this->error("余额不足，请更换其他支付方式");
			}
			M('member')->startTrans();
			try {
				M('member')->where(array('uid'=>UID))->setDec('amount',$info['money']);
				// 消费日志
				payrecord(UID,0,$info['money'],16);
				$data = array(
					'status'	=>	1,
					'pay_time'	=>	time(),
					'pay_type'	=>	'cash'
				);
				M("user_code")->where(array('id'=>$info['id']))->save($data);
				// 更新活动参与数量
				$snatch_info = M("snatch")->find($info['snatch_id']);
				$new_num = $snatch_info['num'] + 1;
				$snatch_data = array(
					'num'	=>	$new_num,
					'progress'=> round((($new_num / $snatch_info['total_num']) * 100),2)
				);
				$result = M("snatch")->where(array('id'=>$info['snatch_id']))->save($snatch_data);
		        if ($result !== false && ($new_num >= $snatch_info['total_num'] || $snatch_info['end_time'] <= time())) {
		            snatch_lottery($snatch_info['id']);
		        }
				M("member")->commit();
				$this->success("支付成功");
			} catch (Exception $e) {
				M("member")->rollback();
				$this->error("支付失败");
			}
		}elseif ($pay_type == 'alipay') {
			header("Content-type: text/html; charset=utf-8");
			require VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/config.php';
			require_once VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/aop/AopClient.php';
			require_once VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/aop/request/AlipayTradeWapPayRequest.php';
			require_once VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/AlipayTradeService.php';
			require_once VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/AlipayTradeWapPayContentBuilder.php';

			$return_url = "http://".$_SERVER['HTTP_HOST']. U("pay_success");
			$notify_url = "http://".$_SERVER['HTTP_HOST'].U("alipayNotify");

		    $payRequestBuilder = new \AlipayTradeWapPayContentBuilder();
		    $payRequestBuilder->setBody("幸运码");
		    $payRequestBuilder->setSubject("幸运码");
		    $payRequestBuilder->setOutTradeNo($info['pay_sn']);
		    $payRequestBuilder->setTotalAmount($info['money']);
		    $payRequestBuilder->setTimeExpress("1m");

		    $payResponse = new \AlipayTradeService($config);
		    $result=$payResponse->wapPay($payRequestBuilder,$return_url,$notify_url);
		    return ;
		}elseif($pay_type == 'jtpay'){
			header("Content-type: text/html; charset=utf-8");
			vendor("jtpay/jtpay");
			$return_url = "http://".$_SERVER['HTTP_HOST']. U("pay_success");
			$notify_url = "http://".$_SERVER['HTTP_HOST'].U("jtpayNotify");
			$jtpay = new \Jtpay('10226737','C7AFD2BF2B2180E9E750AD47B9A78565','长沙树上蛙网络科技有限公司');
			$jtpay->setProduct("幸运码");
			$jtpay->setOrdersn($info['pay_sn']);
			$jtpay->setMoney($info['money']);
			$jtpay->setPayMethod(3);
			$jtpay->setReturnUrl($return_url);
			$jtpay->setNotifyUrl($notify_url);
			$jtpay->getSign();
			$html = $jtpay->buildRequestForm();
			echo $html;
		    return ;
		}
	}
	public function pay_success(){
		$this->display();
	}
	/**
	 * 获取微信支付信息
	 * @param  [type] $pay_sn [description]
	 * @param  [type] $money        [description]
	 * @return [type]               [description]
	 */
	private function getWxpayinfo($pay_sn,$money){
		header("Content-type: text/html; charset=utf-8");
		vendor("Weixinpay/WxPayJsApiPay");
		$tools = new \JsApiPay();
		$openId = session("openId");
		if (empty($openId)) {
			$openId = $tools->GetOpenid();
			session('openId',$openId);
		}
		if ($openId != '') {
			$input = new \WxPayUnifiedOrder();
			$input->SetBody("幸运码支付");
			$input->SetAttach("幸运码支付");
			$input->SetOut_trade_no($pay_sn);
			$input->SetTotal_fee($money * 100);
			$input->SetTime_start(date("YmdHis"));
			$input->SetTime_expire(date("YmdHis", time() + 600));
			$input->SetGoods_tag("幸运码支付");
			$input->SetNotify_url("http://".$_SERVER['HTTP_HOST']."/Home/pay/wxNotify.html");
			$input->SetTrade_type("JSAPI");
			$input->SetOpenid($openId);
			$order = \WxPayApi::unifiedOrder($input);
			$jsApiParameters = $tools->GetJsApiParameters($order);
			return $jsApiParameters;
		}else{
			return "";
		}
	}
	public function alipayNotify(){
		require VENDOR_PATH.'/alipay/config.php';
		require_once VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/aop/AopClient.php';
		require_once VENDOR_PATH.DIRECTORY_SEPARATOR.'alipay/AlipayTradeService.php';
		$arr=$_POST;
		$alipaySevice = new \AlipayTradeService($config); 
		$alipaySevice->writeLog(var_export($arr,true));
		$result = $alipaySevice->check($arr);
		if($result) {
			$out_trade_no = $_POST['out_trade_no'];
			//支付宝交易号
			$trade_no =  $_POST['trade_no'];
			// 支付金额
			$buyer_pay_amount =  $_POST['buyer_pay_amount'];
			//交易状态
			$trade_status =  $_POST['trade_status'];
		    if($_POST['trade_status'] == 'TRADE_FINISHED') {
		    }else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
		    	snatchPayCallBack($out_trade_no,$buyer_pay_amount,$trade_no,'alipay');
		    }
			echo "success";
		}else {
		    //验证失败
		    echo "fail";
		}
		exit();
	}
	/**
	 * 微信支付回调
	 * @return [type] [description]
	 */
	public function wxNotify(){
		vendor("Weixinpay/WxPayNotify");
		$notify = new \WxPayNotify();
		$notify->Handle();
	}
	/**
	 * 竣通支付回调
	 * @return [type] [description]
	 */
	public function jtpayNotify(){
		header("Content-type: text/html; charset=utf-8");
		vendor("jtpay/jtpayNotify");
		$jtpayNotify = new \JtpayNotify('10226737','C7AFD2BF2B2180E9E750AD47B9A78565');
		$check = $jtpayNotify->checkSign();
		if ($check) {
			$pay_sn = I("p2_order");
			$money = I("p3_money");
			$trade_no = I("p5_jtpayorder");
			$result = snatchPayCallBack($pay_sn,$money,$trade_no,'jtpay');
			if ($result) {
				echo "success";
			}else{
				echo "error,update pay error!";
			}
		}else{
			echo "error,checkSign error!";
		}
		exit();
	}
}